angular.module('chat.services',[])
    //定义stomp 客户端服务
    .factory('StompClient',['$q', function ($q){

        //声明stompClient
        var stompClient;
        //声明定义通讯Socket对象作为StompClient服务对象返回
        var wrappedSocket={
            //定义初始化方法
            init:function(url){
                stompClient = Stomp.over(new SockJS(url));
            },
            //定义连接方法,返回$q对象
            connect:function(){

                //$q中传入的毁掉函数的第一个参数用来渲染成功信息，第二个参数用来渲染失败信息
                return $q(function(resolve, reject){

                    if (!stompClient) {
                        reject("STOMP 客户端创建失败");
                    } else {
                        stompClient.connect({}, function (frame) {
                            resolve(frame);
                        }, function (error) {
                            reject("STOMP 传输协议错误 " + error);
                        });
                    }

                });

            },
            //定义断开连接方法
            disconnect: function() {
                stompClient.disconnect();
            },
            //定义订阅方法 destination订阅的地址
            subscribe:function(destination){

                //定义消息装饰器
                var deferred = $q.defer();
                if (!stompClient) {
                    deferred.reject("STOMP 客户端不能创建");
                } else {
                    stompClient.subscribe(destination, function (message) {
                        deferred.notify(JSON.parse(message.body));

                        //deferred.resolve(JSON.parse(message.body));

                    });
                }
                return deferred.promise;

            },
            //定义客户端发送消息方法
            send: function (destination, headers, object) {
                stompClient.send(destination, headers, object);
            }

        }

        return wrappedSocket;


    }])
    //定义聊天服务
    .factory('ChatService',['StompClient','$q', function (stompClient, $q){

        //创建聊天服务对象并返回
        return {
            connect: function (url) {
                stompClient.init(url);
                return stompClient.connect().then(function (frame) {
                    return frame.headers['user-name'];
                });
            },
            disconnect: function() {
                stompClient.disconnect();
            },
            welcome: function () {
                return stompClient.subscribe("/app/welcome");
            },
            room: function () {
                return stompClient.subscribe("/topic/public");
            },
            mine: function () {
                return stompClient.subscribe("/user/message/info");
            },
            error: function () {
                return stompClient.subscribe("/user/message/error");
            },
            send: function(msg) {
                return stompClient.send("/app/send", {}, JSON.stringify(msg));
            }

        }

    }]);